import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:get/get.dart';
import 'package:get/get_connect/http/src/utils/utils.dart';
import 'package:yysk_app/model/pay_model/access_info_query_model.dart';
import 'package:yysk_app/model/pay_model/bank_card_list_model.dart';
import 'package:yysk_app/model/pay_model/cashier_info_query_model.dart';
import 'package:yysk_app/model/pay_model/cashier_route_query_model.dart';
import 'package:yysk_app/model/pay_model/payment_order_pay_confirm_model.dart';
import 'package:yysk_app/model/pay_model/payment_order_pay_model.dart';
import 'package:yysk_app/model/pay_model/user_register_query_model.dart';
import 'package:yysk_app/net/api/pay_url.dart';
import 'package:yysk_app/net/api/product_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/main/main_page.dart';
import 'package:yysk_app/pages/nft_pages/pay_pages/add_bank_card_hf/add_bank_card_hf_page.dart';
import 'package:yysk_app/pages/nft_pages/pay_pages/confirm_payment/bank_pay_code_widget.dart';
import 'package:yysk_app/pages/nft_pages/pay_pages/pay_order/pay_order_page.dart';
import 'package:yysk_app/pages/nft_pages/pay_pages/result_payment/result_payment_page.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_exchange_psw.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_real_name_auth_page.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/wallet/wallet_page.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:oktoast/oktoast.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:yysk_app/utils/transaction_password_page.dart';

import '../../wallet_pages/enterprise_auth_zhifu/my_webview_zhifu_pay.dart';
import '../../wallet_pages/enterprise_auth_zhifu/my_webview_zhifu_user_page.dart';
import '../add_bank_card_zf/add_bank_card_zf_page.dart';

class ConfirmPaymentController extends GetxController {
  final txt = '确认支付'.obs;
  final payMethodChoose = ''.obs; //默认选择列表第一个
  late RxBool isRead = true.obs;
  final payInfo = Rx<CashierInfoQueryModel?>(null); //订单信息
  final payList = RxList<CashierRouteQueryData?>([]); //支付列表
  var chooseType = '0'.obs;
  var sn = ''.obs;
  var type = ''.obs;
  var token = ''.obs; //用户token
  var cashierToken = ''.obs; //cahs数据token
  var accessToken = ''.obs; //acc数据token
  var uuid = ''.obs; //uuid
  var businessType = ''.obs; // 业务类型
  var clientType = ''.obs; // 客户端类型
  var count = 0.obs;
  var payMethod = ''.obs;
  var channel = 'HUIFU'.obs; //支付类型 //HUIFU汇付  默认汇付
  //新支付汇付
  //邀请码输入框控制器invited
  final TextEditingController codeController = TextEditingController();
  var payCode = ''.obs;
  final isFocused = false.obs;
  //判断是否聚焦
  final FocusNode focusNode = FocusNode();
  var smsBtnText = '获取验证码'.obs;
  Timer? _timer;
  int _seconds = 0;
  var payCards = RxList<BankCardListModel>();
  var mobile = ''.obs;
  var drarwCount = 0.obs;
  var payNo = ''.obs;

  @override
  // ignore: unnecessary_overrides
  void onInit() {
    super.onInit();
    cashierToken.value = Get.parameters['cashierToken'] ?? '-1';
    accessToken.value = Get.parameters['accessToken'] ?? '-1';
    businessType.value = Get.parameters['businessType'] ?? 'other';
    clientType.value = Get.parameters['clientType'] ?? 'web';

    uuid.value = '${new DateTime.now().millisecondsSinceEpoch}';
    orderInfo().then((res) {
      getInfoQuery();
      getRouteQuery();
      getBankList(channel.value);
    });
    //监听聚焦
    focusNode.addListener(() {
      isFocused.value = focusNode.hasFocus;
    });
    if (businessType.value != 'PHYSICAL_GOODS') {
      isRead.value = true;
    }
  }

  @override
  // ignore: unnecessary_overrides
  void onClose() {
    super.onClose();
    _timer?.cancel();
    codeController.dispose();
  }

  void getSmsCode() {
    if (_seconds > 0) return;
    // TODO: 请求服务器发送验证码
    _seconds = 60;
    smsBtnText.value = '60s';
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      _seconds--;
      if (_seconds <= 0) {
        timer.cancel();
        smsBtnText.value = '获取验证码';
      } else {
        smsBtnText.value = '${_seconds}s';
      }
    });
  }

  payOrder() {
    if (isRead.value == false) {
      showToast('请同意并阅读免责声明');
      return;
    }
    var type = '';
    for (var element in payList) {
      if (element?.isSelect == true) {
        type = element!.payMethod!; //用payChannel
        payMethodChoose.value = element.payChannel!;
        payMethod.value = type;
      }
    }
    if (type == 'WECHAT') {
      payWx(type);
    } else if (type == 'ALIPAY') {
      payAli(type);
    } else if (type == 'DIN_PAY') {
      //智付支付
      payZhifu(type);
    } else if (type == 'DEBIT_CARD') {
      //汇付支付
      if (payCards.isEmpty) {
        // showToast('请先绑定银行卡');
        toAddAdress(type);
        return;
      }
      showBankPayCodeSheet();
    } else if (type == 'BALANCE') {
      TransactionPasswordDialog.show(
        Get.context!,
        onCompleted: (password) {
          verifySecurityPassword(password, type);
        },
        onCancel: () {},
      );
    }
  }

  //校验交易密码是否正确
  verifySecurityPassword(password, type) async {
    http.netFetch<dynamic>(
      ProductApi.verifySecurityPassword,
      params: {'payPassword': password},
      method: Method.post,
      success: (result) {
        if (result.code == 200) {
          payBALANCE(type);
        }
      },
    );
  }

  //支付余
  Future payBALANCE(String payMethod) async {
    ConfirmPaymentController confirmController = Get.find();

    await http.netFetch<PaymentOrderPayModel>(
      PayUrl.orderPay,
      method: Method.post,
      params: {
        'userToken': confirmController.token.value,
        'cashierToken': confirmController.cashierToken.value,
        'payMethod': payMethod,
        'returnUrl': 'https://yysk.com/', //暂时不用
        'orderNo': payInfo.value?.outTradeNo,
      },
      success: (res) async {
        if (res.code == 200) {
          Get.toNamed(
            '${ResultPaymentPage.path}?buyNow=1&outTradeNo=${payInfo.value?.outTradeNo}',
            arguments: {'buyNow': '1', "outTradeNo": payInfo.value?.outTradeNo},
          );
        }
      },
    );
  }

  //去实名
  toSm({required BuildContext context}) async {
    await showConfirmDialog(
      context: context,
      message: '请先完成实名认证',
      messages: [],
      fontSize: 16,
      actions: [
        ActionModel(
          label: '取消',
          colorStart: AppColors.backgroundColorGreyF8,
          colorEnd: AppColors.backgroundColorGreyF8,
          fontColor: AppColors.fontColor,
          onPressed: () {},
        ),
        ActionModel(
          label: '立即认证',
          onPressed: () {
            Get.toNamed(SettingRealNameAuthPage.path);
          },
        ),
      ],
    );
  }

  Future payWx(String payMethod) async {
    ConfirmPaymentController confirmController = Get.find();
    Get.toNamed(
      '${ResultPaymentPage.path}?buyNow=1&outTradeNo=${payInfo.value?.outTradeNo}',
      arguments: {'buyNow': '1', "outTradeNo": payInfo.value?.outTradeNo},
    );
    // String topic =
    //     "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxbe0dae6128c4ba7f&redirect_uri=https://pay.test.sz-jh.com/payOrder?userToken=${confirmController.token.value}&cashierToken=${confirmController.cashierToken.value}&response_type=code&scope=snsapi_base&state=123#wechat_redirect";

    String test =
        'weixin://dl/business/?appid=wxbe0dae6128c4ba7f&path=pages/index/index?userToken=${confirmController.token.value}&cashierToken=${confirmController.cashierToken.value}';
    // launch(test);
    try {
      await launch(test); // 直接跳转，不判断是否可跳
      Get.toNamed(
        '${ResultPaymentPage.path}?buyNow=1&outTradeNo=${payInfo.value?.outTradeNo}',
        arguments: {'buyNow': '1', "outTradeNo": payInfo.value?.outTradeNo},
      );
    } catch (e) {
      Get.snackbar('跳转失败', '请先安装微信');
      // 处理跳转失败的逻辑（如提示用户重新安装微信）
    }
  }

  Future payAli(String payMethod) async {
    ConfirmPaymentController confirmController = Get.find();

    await http.netFetch<PaymentOrderPayModel>(
      PayUrl.orderPay,
      method: Method.post,
      params: {
        'userToken': confirmController.token.value,
        'cashierToken': confirmController.cashierToken.value,
        'payMethod': payMethod,
        'returnUrl': 'https://yysk.com/', //暂时不用
        'orderNo': payInfo.value?.outTradeNo,
      },
      success: (res) async {
        if (res.code == 200) {
          String topic = "alipays://platformapi/startapp?saId=10000007&qrcode=";

          try {
            await launch('$topic${res.data?.payParams}'); // 直接跳转，不判断是否可跳
            Get.toNamed(
              '${ResultPaymentPage.path}?buyNow=1&outTradeNo=${payInfo.value?.outTradeNo}',
              arguments: {
                'buyNow': '1',
                "outTradeNo": payInfo.value?.outTradeNo,
              },
            );
          } catch (e) {
            // showToast('请先安装支付宝');
            Get.snackbar('跳转失败', '请先安装支付宝');
            // 处理跳转失败的逻辑（如提示用户重新安装支付宝）
          }
        }
      },
    );
  }

  Future payZhifu(String payMethod) async {
    ConfirmPaymentController confirmController = Get.find();

    await http.netFetch<PaymentOrderPayModel>(
      PayUrl.orderPay,
      method: Method.post,
      params: {
        'userToken': confirmController.token.value,
        'cashierToken': confirmController.cashierToken.value,
        'payMethod': payMethod,
        'returnUrl': 'https://yysk.com/', //暂时不用
        'orderNo': payInfo.value?.outTradeNo,
      },
      success: (res) async {
        if (res.code == 200) {
          try {
            Get.offNamed(
              '${MyWebViewZhifuPayPage.path}?url=${Uri.encodeComponent(res.data?.payUrl.toString() ?? '')}&outTradeNo=${payInfo.value?.outTradeNo}',
              arguments: {
                'url': Uri.encodeComponent(res.data?.payUrl.toString() ?? ''),
                'outTradeNo': payInfo.value?.outTradeNo,
              },
            );
          } catch (e) {
            // showToast('请先安装支付宝');
            Get.snackbar('跳转失败', '请先安装支付宝');
            // 处理跳转失败的逻辑（如提示用户重新安装支付宝）
          }
        }
      },
    );
  }

  //获取权限信息查询
  Future<dynamic> orderInfo() async {
    try {
      await http.netFetch<AccessInfoQueryModel>(
        PayUrl.accessInfoQuery,
        method: Method.post,
        params: {'accessToken': accessToken.value, 'uuid': uuid.value},
        success: (result) {
          if (result.code == 200) {
            GlobalController globalController = Get.find();
            token.value = result.data!.userToken!;

            globalController.saveXPayToken(result.data!.userToken!);
            return result;
          } else {
            showToast('获取失败');
            return null;
          }
        },
      );
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  //查询收银台信息
  getInfoQuery() async {
    try {
      await http.netFetch<CashierInfoQueryModel>(
        PayUrl.infoQuery,
        method: Method.post,
        params: {
          "cashierToken": cashierToken.value,
          "userToken": token.value,
          "uuid": uuid.value,
        },
        success: (result) {
          payInfo.value = result.data;
          return result;
        },
      );
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  //查询订单支付路由
  getRouteQuery() async {
    try {
      await http.netFetch<CashierRouteQueryModel>(
        PayUrl.routeQuery,
        method: Method.post,
        params: {
          "businessType": businessType.value,
          "cashierToken": cashierToken.value,
          "clientType": clientType.value,
          "userToken": token.value,
        },
        success: (result) {
          payList.value = result.data!.data!;
          if (result.data!.data!.isNotEmpty) {
            bool isOver = false;
            for (var element in result.data!.data!) {
              if (element.payMethod == 'DEBIT_CARD') {
                element.isSelect = true;
                payMethod.value = element.payMethod ?? '';
                isOver = true;
              }
            }
            if (!isOver) {
              payList[0]!.isSelect = true;
              payMethod.value = payList[0]!.payMethod ?? '';
              channel.value = payList[0]!.payChannel ?? '';
            }
          }
          return result;
        },
      );
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  //是否开通钱包
  Future<dynamic> isOpenWallet({bool isAddBank = false}) async {
    try {
      await http.netFetch<UserRegisterQueryModel>(
        PayUrl.registerQuery,
        method: Method.post,
        params: {'plat': 'USER', 'channel': channel.value},
        success: (result) {
          if (result.code == 200 && result.data?.status == true) {
            if (!isAddBank) {
              payOrder();
            } else {
              if (channel.value == 'DEBIT_CARD') {
                //汇付
                Get.toNamed(
                  '${AddBankCardHfPage.path}?comeFrom=mallAdd',
                  arguments: {'comeFrom': 'mallAdd'},
                );
              } else if (channel.value == 'DIN_PAY') {
                //智付
                Get.toNamed(
                  '${AddBankCardZfPage.path}?comeFrom=mallAdd',
                  arguments: {'comeFrom': 'mallAdd'},
                );
              }
            }
          } else {
            showConfirmDialog(
              context: Get.context!,
              message: '请先开通钱包',
              messages: ['开通后请前往藏品待支付订单中支付'],
              actions: [
                ActionModel(
                  label: '取消',
                  onPressed: () {},
                  colorStart: AppColors.backgroundColorGreyF8,
                  colorEnd: AppColors.backgroundColorGreyF8,
                  fontColor: AppColors.fontColor,
                ),
                ActionModel(
                  label: '前往开通',
                  onPressed: () {
                    try {
                      Get.until((route) => Get.currentRoute == MainPage.path);
                    } catch (e) {
                      Get.offAllNamed(MainPage.path);
                    }
                    Get.toNamed(WalletPage.path);
                  },
                ),
              ],
            );
          }
        },
      );
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  //是否添加银行卡
  Future<dynamic> toAddAdress(String payChannel) async {
    showConfirmDialog(
      context: Get.context!,
      message: '请添加银行卡',
      messages: [],
      fontSize: 16,
      actions: [
        ActionModel(label: '取消', onPressed: () {}),
        ActionModel(
          label: '前往绑卡',
          onPressed: () {
            if (payChannel == 'DEBIT_CARD') {
              //汇付
              Get.toNamed(
                '${AddBankCardHfPage.path}?comeFrom=mallAdd',
                arguments: {'comeFrom': 'mallAdd'},
              );
            } else if (payChannel == 'DIN_PAY') {
              //智付
              Get.toNamed(
                '${AddBankCardZfPage.path}?comeFrom=mallAdd',
                arguments: {'comeFrom': 'mallAdd'},
              );
            }
          },
        ),
      ],
    );
  }

  Future getBankList(String channel) async {
    await http.netFetch<List<BankCardListModel>>(
      PayUrl.bankCardList,
      method: Method.post,
      params: {'channel': channel, 'plat': 'USER', 'bindType': 'PAY'},
      success: (res) {
        if (res.data!.isNotEmpty) {
          payCards.value = res.data ?? [];
          payCards[0].isSelect = true;
          mobile.value = payCards[0].mobile ?? '';
        } else {
          payCards.value = [];
          mobile.value = '';
        }
      },
    );
  }

  Future getbankCardId() async {
    String bankCardId = '';
    for (var element in payCards) {
      if (element.isSelect == true) {
        bankCardId = '${element.id}';
      }
    }
    await http.netFetch<PaymentOrderPayModel>(
      PayUrl.orderPay,
      method: Method.post,
      params: {
        "userToken": token.value,
        "cashierToken": cashierToken.value,
        'payMethod': payMethod.value,
        'returnUrl': 'https://111.com/', //暂时不用
        "bankCardId": bankCardId,
      },
      success: (res) {
        if (res.code == 200) {
          payNo.value = res.data?.payNo ?? '';
          getSmsCode();
          showToast('短信发送成功');
        }
      },
    );
  }

  pay() {
    if (payNo.value == '') {
      showToast('请先获取验证码');
      return;
    }
    if (isRead.value == false) {
      showToast('请同意并阅读免责声明');
      return;
    }
    ConfirmPaymentController confirmController = Get.find();
    if (codeController.text == '') {
      showToast('验证码为空');
      return;
    }
    http.netFetch<PaymentOrderPayConfirmModel>(
      PayUrl.orderPayConfirm,
      method: Method.post,
      params: {
        'userToken': confirmController.token.value,
        'payMethod': payMethod.value,
        'smsCode': codeController.text,
        "payNo": payNo.value,
      },
      success: (result) {
        if (result.code == 200) {
          Get.toNamed(
            '${ResultPaymentPage.path}?buyNow=1&outTradeNo=${result.data?.outTradeNo}',
            arguments: {'buyNow': '1', "outTradeNo": result.data?.outTradeNo},
          );
        }
      },
    );
  }
}
